<?php

/**
 * Script used to update the user information in the database
 */

session_start();
// Return json encoded data
header ('Content-type: application/json');
define ('SALT', 'ThisIsth3sal7'); // NEVER CHANGE!
define ('SITEKEY', 'ASiteSpecificArbitraryLengthStringThatIsUsedToSeedTheHashingAlgorithm'); //NEVER CHANGE!
require_once '../core/db.php';
$sql = "SELECT * FROM siteUsers WHERE userID=:usrID";
$query = $db -> prepare($sql);
$query -> bindParam(':usrID', $_SESSION["user"]);
$query -> execute();
$old = $query -> fetch();
$query -> closeCursor();
if(isset($old['userName'])){
	$change = false;
	
	if(isset($_POST['pwd']) && $_POST['pwd']!= "" && isset($_POST['oldpwd']) && $_POST['oldpwd']!= ""){
			$oldpwd = $_SESSION['user'].$_POST['oldpwd'].SALT;
			$oldpwd = hash_hmac('sha512', $oldpwd, SITEKEY);
			if($old['password'] == $oldpwd){
				$pwd = $_SESSION['user'].$_POST['pwd'].SALT;
				$pwd = hash_hmac('sha512', $pwd, SITEKEY);
				$password = $pwd;
				$change =  true;
		}else{
			$password = $old['password'];
		}		
	}else{
		$password = $old['password'];
	}
	if(isset($_POST['email']) &&  $_POST['email'] != $old['email']){
		$email = $_POST['email'];
		$change =  true;
	}else{
		$email = $old['email'];
	}
	if(isset($_POST['name']) && $_POST['name'] != $old['userRealName']){
		$name = $_POST['name'];
		$change =  true;
	}else{
		$name = $old['userRealName'];
	}
	if(isset($_POST['town']) && $_POST['town'] != $old['homeTown']){
		$town = $_POST['town'];
		$change = true;
	}else{
		$town = $old['homeTown'];
	}
	if( $change == true ){
		$sql ="UPDATE siteUsers SET email=:email, password=:pwd, userRealName=:name, homeTown=:town WHERE userID=:uid";
		$query = $db -> prepare($sql);
		$query -> bindParam(":email", $email);
		$query -> bindParam(":pwd", $password);
		$query -> bindParam(":name", $name);
		$query -> bindParam(":town", $town);	
		$query -> bindParam(":uid", $old['userID']);
		$res = $query -> execute();
		if($res){
			die(json_encode(array("response" => "true")));
		}	
	}else{
		die(json_encode(array("response" => "noChanges")));
	}	
} else {
	die(json_encode(array("response" => "Could not find user!")));
}
?>